<template>
  <!-- 添加题弹框 -->
  <el-drawer
    :title="label + '多选题'"
    size="39%"
    :visible.sync="dialog"
    label="rtl"
    custom-class="demo-drawer"
    :before-close="Close"
  >
    <div class="demo-drawer__content">
      <el-form
        ref="form"
        style="overflow-y: scroll; overflow-x: hidden; max-height: 80vh"
        :rules="rules"
        :model="form"
        label-width="80px"
        class="item"
      >
        <el-form-item label="题库" prop="category">
          <!-- 选择题库 -->
          <el-select
            v-model="form.category"
            placeholder="选择题库"
            @change="getcategory"
          >
            <el-option
              v-for="e in categoryOptions"
              :key="e.value"
              :label="e.label"
              :value="e.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目" prop="content">
          <el-input v-model="form.content" type="textarea" />
        </el-form-item>
        <!-- 利用循环 -->
        <!-- 选项 -->
        <el-form-item
          v-for="(domain, index) in form.options"
          :key="domain.key"
          :label="'选项' + letterArray[index]"
          :prop="'options.' + index + '.content'"
          :rules="{
            required: true,
            message: '选项不能为空',
            trigger: 'blur'
          }"
          class="item"
        >
          <el-input v-model="domain.content">
            <el-button
              slot="append"
              class="el-icon-remove-outline"
              @click.prevent="removeDomain(domain)"
            />
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="el-icon-plus"
            style="cursor: pointer; border: 1px dashed #dcdfe6"
            round
            @click="addDomain"
          >添加选项</el-button>
        </el-form-item>
        <!--  -->
        <el-form-item label="题解">
          <el-input v-model="form.solution" type="textarea" />
        </el-form-item>
        <div class="box">
          <el-row>
            <el-col :span="8">
              <el-form-item label="答案" prop="formanswer">
                <el-checkbox-group v-model="formanswer" @change="group">
                  <el-checkbox
                    v-for="(item, index) in form.options"
                    :key="index"
                    :label="item.opt"
                  />
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="分数" prop="score">
                <el-input
                  v-model="form.score"
                  placeholder="请输入分数"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="难度" prop="difficulty">
                <el-select
                  v-model="form.difficulty"
                  placeholder="选择难度"
                  class="select"
                >
                  <el-option
                    v-for="item in difficulty"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" @click="handleClose"> 确 定 </el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { pushsaveList } from '@/api/ts/question.js'
import { listDictTreeItem, CompileUpdate } from '@/api/ts/question.js'
export default {
  props: ['dialogmultiple'],
  data() {
    var checkFormAnswer = (rule, value, callback) => {
      if (!this.formanswer || this.formanswer.length === 0) {
        callback(new Error('至少选择一个选项'))
      }
      callback()
    }
    var checkOptions = (rule, value, callback) => {
      this.form.options.map((item) => {
        if (item.content === '') {
          callback(new Error('内容不可为空'))
        }
      })
      callback()
    }
    return {
      letterIndex: 0,
      letterArray: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
      label: '',
      type: '2',
      radio: '1',
      dialog: false,
      loading: false,
      value: '',
      categoryOptions: [],
      sort: '',
      examinationQuestionId: '',
      difficulty: [
        { value: 1, label: '容易' },
        { value: 2, label: '常规' },
        { value: 3, label: '较难' },
        { value: 4, label: '很难' }
      ],
      answerdata: [],
      answerdataList: {},
      formanswer: [],
      form: {
        category: '',
        content: '',
        solution: '',
        score: 1,
        answer: [],
        difficulty: 1,
        options: []
      },
      formLabelWidth: '80px',
      timer: null,
      rules: {
        content: [
          { required: true, message: '输入内容不可为空', trigger: 'blur' }
        ],
        options: [{ required: true, validator: checkOptions, trigger: 'blur' }],
        answer: [{ required: true, message: '请选择答案', trigger: 'change' }],
        score: [
          { required: true, message: '请输入分数', trigger: 'change' },
          { pattern: /^[1-9][0-9]{0,1}$/, message: '请输1-99之间的正整数', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择题库', trigger: 'change' }
        ],
        formanswer: [
          {
            required: true,
            validator: checkFormAnswer,
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    dialogmultiple(val) {
      if (val.optkey) {
        this.letterIndex = val.optkey
      }
      this.dialog = val.dialogmultiple
      this.categoryOptions = val.categoryOptions
      this.label = val.label
      this.sort = val.sort
      this.examinationQuestionId = val.examinationQuestionId
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      if (val.sort === '1') {
        Object.assign(this.$data.form, this.$options.data().form)
        for (let i = 0; i < 4; i++) {
          this.addDomain()
        }
        this.formanswer = []
      } else if (val.sort === '2') {
        this.form = val.form
        const data = val.form.answer
        if (data !== '') {
          this.formanswer = data.split(',')
        }
      }
    }
  },
  mounted() {
    this.dialogsingle
    this.listDictTreeItem()
  },
  methods: {
    // // 动态添加选项
    removeDomain(item) {
      var index = this.form.options.indexOf(item)
      if (index !== -1) {
        this.form.options.splice(index, 1)
      }
      this.letterIndex = this.letterIndex - 1
      for (let i = 0; i < this.form.options.length; i++) {
        this.form.options[i].opt = this.letterArray[i]
      }
    },
    addDomain() {
      if (this.letterIndex + 1 > this.letterArray.length) {
        this.$message.warning('不支持添加更多的选项')
      } else {
        this.form.options.push({
          opt: this.letterArray[this.letterIndex]
        })
        this.letterIndex = this.letterIndex + 1
      }
    },
    //
    fillin() {
      this.dialog = true
    },
    handleClose(form) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.sort === '1') {
            this.pushsaveList()
          } else if (this.sort === '2') {
            this.CompileUpdate()
          }
          this.dialog = false
          this.letterIndex = 0
        } else {
          this.$message.error({
            message: '输入内容不可为空'
          })
        }
      })

      // this.forceUpdate()
    },
    cancelForm() {
      this.dialog = false
      clearTimeout(this.timer)
    },
    // 获取题库列表
    async listDictTreeItem() {
      const dataList = await listDictTreeItem({
        dictGroupCode: 'examination_question_category',
        parentDictId: 0
      })
      this.categoryOptions = dataList.data
    },

    // 获取选中值
    getcategory(e) {
      this.category = e
    },
    // 获取多选值
    group(a) {
      const data = a.toString()
      this.answerdataList = data
    },
    // 提交
    async pushsaveList() {
      const formdata = {
        category: this.form.category,
        type: this.type,
        difficulty: this.form.difficulty,
        content: this.form.content,
        answer: this.answerdataList,
        score: this.form.score,
        solution: this.form.solution,
        options: this.form.options
      }
      try {
        const data = await pushsaveList(formdata)
        if (data.code === 1) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        }
        this.$parent.getList()
      } catch (error) {
        //
      }
    },
    async CompileUpdate() {
      if (this.answerdataList == {}) {
        this.answerdataList = this.form.answer
      }
      const formdata = {
        category: this.form.category,
        type: this.type,
        difficulty: this.form.difficulty,
        content: this.form.content,
        answer: this.answerdataList,
        score: this.form.score,
        solution: this.form.solution,
        options: this.form.options,
        examinationQuestionId: this.examinationQuestionId
      }
      try {
        const data = await CompileUpdate(formdata)
        if (data.code === 1) {
          this.$message({
            message: '编辑成功',
            type: 'success'
          })
        }
        this.$parent.getList()
      } catch (error) {
        //
      }
    },
    Close(done) {
      this.letterIndex = 0
      if (this.label === '添加') {
        this.$confirm('确认关闭？')
          .then((_) => {
            done()
          })
          .catch((_) => {})
      } else {
        done()
      }
    }
  }
}
</script>

<style scoped lang='scss'>
:focus {
  outline: 0;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  flex-wrap: wrap;
}
.demo-drawer__footer {
  text-align: right;
  margin-top: 50px;
  padding: 0 20px;
}
.el-form-item {
  margin-bottom: 20px !important ;
}
</style>>
